package com.tom.mybatis.mapper;

import com.tom.mybatis.config.MapperRegistory;
import com.tom.mybatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author : tom
 * @project: tom-mybatis
 * @date : 2018/11/7 14:54
 */
public class MapperProxy<T> implements InvocationHandler {

    private final SqlSession sqlSession;

    private final Class<T> mapperInterface;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperRegistory.MapperDate mapperDate = sqlSession
                .getConfiguration()
                .getMapperRegistory()
                .get(method.getDeclaringClass().getName() + "." + method.getName());

        if (mapperDate != null) {
            System.out.println(String.format("SQL [ %s ], parameter [%s] ", mapperDate.getSql(), args[0]));
            return sqlSession.selectOne(mapperDate, String.valueOf(args[0]));
        }
        return method
                .invoke(proxy, args);
    }
}
